<template>
    <el-table
        ref="tableRef"
        id="cfscntrs-table-cfscntrs"
        :data="tableData"
        v-bind="tableDefaultAttribute"
        row-key="id"
        :max-height="tableHeight"
        table-layout="auto"
        :summary-method="getSummaries"
        show-summary
        @sort-change="handleSortChange"
    >
        <template #empty>
            <span>无数据</span>
        </template>
        <el-table-column type="selection" width="55" :align="'center'" />
        <template v-for="col in tableColumns" :key="col.prop">
            <el-table-column
                v-if="!col.isHidden"
                :align="col.align"
                :prop="col.prop"
                :label="col.label"
                :fixed="col.fixed"
                :formatter="col.formatter"
                :type="col.type"
                :width="col.width"
            >
                
            </el-table-column>
        </template>
    </el-table>
    <el-button-group class="bg">
        <el-space>
            <el-button
                class="btn"
                type="primary"
                :icon="Search"
                @click="onQuery"
                >查询</el-button
            >
            <el-button
                class="btn"
                type="primary"
                :icon="Scissor"
                @click="onFix">修箱明细</el-button
            >
            <el-button
                class="btn"
                type="primary"
                :icon="Sell"
                @click="onFixSend">修箱报价提交</el-button
            >
            <el-dropdown @command="handleCommand">
                <el-button type="primary">
                    导出 Excel<el-icon class="el-icon--right"
                        ><arrow-down
                    /></el-icon>
                </el-button>
                <template #dropdown>
                    <el-dropdown-menu>
                        <el-dropdown-item command="current"
                            >当前页</el-dropdown-item
                        >
                        <el-dropdown-item command="all">全部</el-dropdown-item>
                    </el-dropdown-menu>
                </template>
            </el-dropdown>
        </el-space>
    </el-button-group>
    <div class="page">
        <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[50, 100, 150, 200]"
            layout="sizes, prev, pager, next"
            :total="totalnum"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
    </div>

    <el-dialog
        v-model="dialogQueryVisible"
        title="箱查询"
        draggable
        destroy-on-close
    >
        <QueryForm
            :queryItems="queryItems"
            :tableID="tableRef!.$el.id"
            @yh-closedialog="onCloseDialog"
        ></QueryForm>
    </el-dialog>
    <el-dialog
        v-model="dialogFixVisible"
        title="箱修理明细"
        draggable
        destroy-on-close
        width="80%"
    >
        <FixList
            :cntr_no="paramCntrNo"
            :caller="'CfsCntrs'"
            
        ></FixList>
    </el-dialog>
</template>
<script setup lang="ts" name="CfsCntrs">
/**
 * 场站权限下箱查询
 */
import { ref, reactive, onMounted } from 'vue';
import { storeToRefs } from 'pinia';
import { Search, Scissor, Sell } from '@element-plus/icons-vue';
import { forEach, forEachRight, includes, isEmpty } from 'lodash';
import type { CntrModel } from '@/common/types/container';
import {
    tableDefaultAttribute,
    useTableInfo,
    tableColumnDefault,
} from '@/hooks/useTable';
import type { QueryItem, TableColumn } from '@/common/types/app';
import { Request } from '@/app/request';
import { exportExcel, pickQueryFromTable } from '@/common/tools';
import { ElMessage, ElMessageBox, type TableInstance } from 'element-plus';
import { useAppStore } from '@/store/app';
import { transFormatter, formatDate, formatDateTime } from '@/common/tools';
import { tableMaxHeightAdjust } from '@/common/const';
// import FixList from '../repair/FixList.vue';
import FixList from '@/views/cfs/repair/Fixlist.vue';
const {
    cntrOper,
    cntrOwner,
    cntrCorp,
    cntrDam,
    cyCfs,
    SelectOptionReply,
    // cntrStat,
    cntrStatus,
    // refMachine,
} = storeToRefs(useAppStore());

const tableRef = ref<TableInstance>();
const tableData = ref<Array<CntrModel>>([]);
// const paramData = reactive<CntrModel>({});
const paramCntrNo = ref(0);
const tableHeight = ref(100);
const onFormatter = (_row: any, column: any, cellValue: any) => {
    let data: { value: string | number; label: string }[];
    if (column['property'] === 'cntr_oper_cod') {
        data = cntrOper.value;
    } else if (column['property'] === 'dam_id') {
        data = cntrDam.value;
    } else if (column['property'] === 'cfs_cod') {
        data = cyCfs.value;
    } else if (column['property'] === 'cntr_corp_cod') {
        data = cntrCorp.value;
    } else if (column['property'] === 'current_stat') {
        data = cntrStatus.value;
    } else if (column['property'] === 'cntr_owner') {
        data = cntrOwner.value;
    } else if (column['property'] === 'repair_reply_id') {
        data = SelectOptionReply.value;
    } else {
        return cellValue;
    }

    return transFormatter(cellValue, data);
};
const tableColumns = reactive<TableColumn[]>([
    {
        ...tableColumnDefault,
        order: 9,
        prop: 'in_truck_sn',
        label: '进场计划号',
        fixed: 'left',
        noFormField: true,
        width: 120,
    },
    {
        ...tableColumnDefault,
        order: 9,
        prop: 'in_plan_name',
        label: '进场计划名称',
        fixed: 'left',
        noFormField: true,
        width: 150,
    },
    {
        ...tableColumnDefault,
        order: 2,
        prop: 'current_stat',
        label: '箱状态',
        sortable: 'custom',
        fixed: 'left',
        formatter: onFormatter,
        formFieldItemType: 'single',
        optionalValues: cntrStatus.value,
        width: 90,
    },
    {
        ...tableColumnDefault,
        order: 16,
        prop: 'release_no',
        label: '放箱单号',
        fixed: 'left',
        sortable: 'custom',
        width: 200,
    },
    {
        ...tableColumnDefault,
        order: 1,
        prop: 'cntr',
        label: '箱号',
        fixed: 'left',
        sortable: 'custom',
        formFieldItemType: 'input',
        width: 150,
    },
    {
        ...tableColumnDefault,
        order: 1,
        prop: 'repair_reply_id',
        label: '修箱状态',
        sortable: 'custom',
        formatter: onFormatter,
        formFieldItemType: 'single',
        optionalValues: SelectOptionReply.value,
        width: 150,
    },

    {
        ...tableColumnDefault,
        order: 3,
        prop: 'cntr_siz_cod',

        label: '箱尺寸',
        sortable: 'custom',
        width: 80,
    },
    {
        ...tableColumnDefault,
        order: 4,

        prop: 'cntr_typ_cod',
        label: '箱型',
        sortable: 'custom',
        width: 80,
    },

    {
        ...tableColumnDefault,
        order: 10,
        prop: 'to_port_tim',
        label: '进场时间',
        sortable: 'custom',

        formatter: formatDateTime,
        formFieldItemType: 'datetime',
        width: 250,
    },

    {
        ...tableColumnDefault,
        order: 9,
        prop: 'out_truck_sn',
        label: '出场计划号',

        noFormField: true,
        width: 120,
    },
    {
        ...tableColumnDefault,
        order: 9,
        prop: 'out_plan_name',
        label: '出场计划名称',

        noFormField: true,
        width: 150,
    },

    {
        ...tableColumnDefault,
        order: 13,
        prop: 'leav_port_tim',
        label: '离场时间',
        sortable: 'custom',

        formatter: formatDateTime,
        formFieldItemType: 'datetime',
        // optionalValues: cntrDam
        width: 250,
    },

    {
        ...tableColumnDefault,
        order: 5,
        prop: 'cntr_owner',
        label: '箱主',
        sortable: 'custom',
        formatter: onFormatter,
        formFieldItemType: 'single',
        optionalValues: cntrOwner.value,
        width: 200,
    },
    {
        ...tableColumnDefault,
        order: 17,
        prop: 'in_dam_id',
        label: '进场箱况',
        formatter: onFormatter,
        sortable: 'custom',
        formFieldItemType: 'single',
        optionalValues: cntrDam.value,
        width: 100,
    },
    {
        ...tableColumnDefault,
        order: 17,
        prop: 'dam_id',
        label: '当前箱况',
        formatter: onFormatter,

        sortable: 'custom',
        formFieldItemType: 'single',
        optionalValues: cntrDam.value,
        width: 100,
    },
    {
        ...tableColumnDefault,
        order: 9,
        prop: 'bill_no',
        label: '收箱提单号',
        sortable: 'custom',
        width: 200,
    },
    {
        ...tableColumnDefault,
        order: 19,
        prop: 'cntr_date',
        label: '箱制造日期',
        sortable: 'custom',
        formatter: formatDate,
        formFieldItemType: 'date',
        // optionalValues: SelectOptionPlanKind
        width: 250,
    },
    {
        ...tableColumnDefault,
        order: 18,
        prop: 'refmachine_brand',
        label: '机组品牌',
        sortable: 'custom',
        formFieldItemType: 'input',
        width: 160,
    },
    {
        ...tableColumnDefault,
        order: 18,
        prop: 'refmachine_model',
        label: '机组型号',
        sortable: 'custom',
        formFieldItemType: 'input',
        width: 160,
    },

    {
        ...tableColumnDefault,
        order: 19,
        prop: 'refmachine_date',
        label: '机组日期',
        sortable: 'custom',
        formatter: formatDate,
        formFieldItemType: 'date',
        // optionalValues: SelectOptionPlanKind
        width: 250,
    },
]);
const dialogFixVisible = ref(false);
const dialogQueryVisible = ref(false);
let queryWhere = {};

const onRefresh = async () => {
    const req = new Request('堆场箱查询', {
        skip: (currentPage.value - 1) * pageSize.value,
        take: pageSize.value,
        order: orders,
        ...queryWhere,
    });
    const r = await req.post();

    totalnum.value = r.ext;
    tableData.value.length = 0;

    if (!isEmpty(r.obj)) {
        tableData.value = r.obj;
    }
};
const {
    currentPage,
    orders,
    pageSize,
    totalnum,
    handleSizeChange,
    handleCurrentChange,
    handleSortChange,
} = useTableInfo(onRefresh);
onMounted(() => {
    tableHeight.value = window.innerHeight - tableMaxHeightAdjust;
});

const onCloseDialog = async (arg: any) => {
    if (dialogFixVisible.value) {
        dialogFixVisible.value = false;
    }
    if (dialogQueryVisible.value) {
        // 查询
        currentPage.value = 1;
        queryWhere = arg;
        onRefresh();

        dialogQueryVisible.value = false;
    }
};

const handleCommand = async (command: string | number | object) => {
    if (command === 'current') {
        exportExcel('cfscntrs-table-cfscntrs');
    } else {
        const columns = [];
        for (let index = 0; index < tableColumns.length; index++) {
            const element = tableColumns[index];
            columns.push(element.prop);
        }
        const req = new Request('导出堆场箱查询', {
            // skip: (currentPage.value - 1) * pageSize.value,
            // take: pageSize.value,
            order: orders,
            ...queryWhere,
            excelColumn: columns,
        });
        const r = await req.post();
        if (!isEmpty(r.obj)) {
            // tableData.value = r.obj;
            // const url = r.obj; // 后端提供的下载接口
            window.open(r.obj, '_blank');
        }
    }
};

const onQuery = () => {
    dialogQueryVisible.value = true;
};
const onFix = () => {
    const rows: Array<CntrModel> = tableRef.value?.getSelectionRows() || [];
    if (rows.length !== 1) {
        ElMessage.info({
            message: '请选择一个记录',
        });
        return;
    }
    paramCntrNo.value = rows[0].id as number;
    dialogFixVisible.value = true;
}
const onFixSend = async () => {
    const rows: Array<CntrModel> = tableRef.value?.getSelectionRows() || [];
    if (rows.length === 0) {
        ElMessage.info({
            message: '请选择要报价箱号',
        });
        return;
    }
    /* if (rows.length > 3) {
        ElMessage.info({
            message: '一次最多删除3条数据',
        });
        return;
    } */
    const ids = Array<number>();
    const labels = Array<string>();
    forEach(rows, (v: CntrModel) => {
        ids.push(v.id as number);
        labels.push(v.cntr as string);
    });

    const msg = labels.join(',     ');
    // const delids = ids.join(',');
    const cr = await ElMessageBox.confirm(msg, '确认提交如下箱报价', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
    })
        .then(() => {
            return true;
        })
        .catch(() => {
            return false;
        });
    if (cr) {
        //
        const req = new Request('箱修理报价提交', { ids });
        const r = await req.post();
        
    }

}
const getSummaries = () => {
    return ['', `总箱量：${totalnum.value}`];
};
const queryItems: Array<QueryItem> = pickQueryFromTable(tableColumns);
</script>
<style lang="scss" scoped>
.bg {
    margin-top: 10px;

    .btn {
        margin-right: 10px;
    }
}

.page {
    float: right;
    margin-top: 10px;
}
</style>
